package www.sharetime.weshare.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import www.sharetime.weshare.R;
import www.sharetime.weshare.base.BaseActivity;
import www.sharetime.weshare.event.DeleteTagGroupEvent;
import www.sharetime.weshare.fragment.BLBeautifyFragment;
import www.sharetime.weshare.model.BLBeautifyParam;
import www.sharetime.weshare.pictureselector.adapter.FragmentViewPagerAdapter;
import www.sharetime.weshare.tag.DIRECTION;
import www.sharetime.weshare.tag.TagViewGroup;
import www.sharetime.weshare.tag.model.TagGroupModel;
import www.sharetime.weshare.tag.views.ITagView;
import www.sharetime.weshare.utils.BLConfigManager;
import www.sharetime.weshare.utils.L;
import www.sharetime.weshare.utils.UIUtils;
import www.sharetime.weshare.view.CustomViewPager;


/**
 * Created by Administrator on 2017/4/15.
 * 美化图片
 */

public class BLBeautifyImageActivity extends BaseActivity implements View.OnClickListener {
    private static int TXT_NORMAL_COLOR = Color.BLACK;
    private static int TXT_SELECTED_COLOR;


    private enum FUN_TYPE {FILTER, STICKER, TAG, CROP, SCRAWL, EDIT}

    private FUN_TYPE mFunType = FUN_TYPE.FILTER;

    private TextView tvCancle, tvSure;
    private Button btnEditPicTitle;
    private CustomViewPager mViewPager;

    private List<String> imageList;


    private FragmentViewPagerAdapter fAdapter;
    private List<Fragment> fragments;
    private int curPosition;

    private TagViewGroup.OnTagGroupClickListener mTagGroupClickListener;


    @Override
    protected int getLayoutId() {
        return R.layout.bl_activity_beautify_image;
    }


    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);

        //TODO: 给ViewPager添加点击事件
        mViewPager = (CustomViewPager) findViewById(R.id.beautify_image_viewpager);
        tvCancle = (TextView) findViewById(R.id.tv_cancle);
        tvCancle.setOnClickListener(this);
        tvSure = (TextView) findViewById(R.id.tv_sure);
        tvSure.setOnClickListener(this);
        btnEditPicTitle = (Button) findViewById(R.id.btn_title_select);

    }

    @Override
    public void initData() {
        super.initData();
        TXT_SELECTED_COLOR = BLConfigManager.getPrimaryColor();

        imageList = getIntent().getStringArrayListExtra(BLBeautifyParam.KEY);
        fragments = new ArrayList<>();
        for (String path : imageList) {
            Log.e("path", path);
            fragments.add(new BLBeautifyFragment().newInstance(path));
        }
        fAdapter = new FragmentViewPagerAdapter(getSupportFragmentManager(), mViewPager, fragments);
        mViewPager.setAdapter(fAdapter);
        mViewPager.setCurrentItem(curPosition);
        mViewPager.setOffscreenPageLimit(imageList.size());
        setTitleText(curPosition);

        fAdapter.setOnExtraPageChangeListener(new FragmentViewPagerAdapter.OnExtraPageChangeListener() {
            @Override
            public void onExtraPageSelected(int i) {
                curPosition = i;
                setTitleText(curPosition);
            }
        });

        mTagGroupClickListener = new TagViewGroup.OnTagGroupClickListener() {
            @Override
            public void onCircleClick(TagViewGroup group) {
//                toast("点击中心圆");
                Fragment f = fragments.get(curPosition);
                if (f instanceof BLBeautifyFragment) {
                    TagGroupModel model = ((BLBeautifyFragment) f).getTagGroupModel(group);
                    List<TagGroupModel.Tag> tags = model.getTags();
                    List<ITagView> tagViews = group.getTagList();
                    for (int i = 0; i < tagViews.size(); i++) {
                        ITagView tagView = tagViews.get(i);
                        TagGroupModel.Tag tag = tags.get(i);
                        tag.setDirection((tag.getDirection() + 1) % 11 == 0 ? 1 : tag.getDirection() + 1);
                        int direction = tag.getDirection();
                        tagView.setDirection(DIRECTION.valueOf(direction));
                    }
                }

                group.invalidate();
                group.requestLayout();
            }

            @Override
            public void onTagClick(TagViewGroup group, ITagView tag, int index) {
                Fragment fragment = fragments.get(curPosition);
                TagGroupModel model = ((BLBeautifyFragment) fragment).getTagGroupModel(group);

                ArrayList<TagGroupModel.Tag> tags = (ArrayList<TagGroupModel.Tag>) model.getTags();

                for (int i = 0; i < tags.size(); i++) {
                    L.et("tag", tags.get(i).toString());
                }

                Bundle bundle = new Bundle();
                bundle.putParcelable("model", model);

                //TODO: 点击编辑标签，跳转到标签编辑页面，同时把当前标签数据传递给下一个页面，进行回显。编辑完成后，回到这个页面，先删除旧的。再添加新的

                /**
                 * 分几种情况：
                 *
                 * 1. 有1组标签的。
                 * 2. 多组标签，需要传递过去是编辑的那个标签，回显的时候，删除对应标签。（要记住编辑、删除的是哪个标签）
                 * 3. 传递过去回显在AddTagActivity页面上。
                 * 4. 编辑好之后，再回来不是——添加标签，而是修改，需要删除原来的标签，add一个新的标签组。
                 * 5. AddTagActivity的打开方式有两种： 一种点击屏幕图片，打开添加标签组；第二，点击标签，打开标签编辑页面；
                 */
                UIUtils.startActivity(BLBeautifyImageActivity.this, AddTagActivity.class, bundle);
            }

            @Override
            public void onScroll(TagViewGroup group, float percentX, float percentY) {
                Fragment f = fragments.get(curPosition);
                if (f instanceof BLBeautifyFragment) {
                    TagGroupModel model = ((BLBeautifyFragment) f).getTagGroupModel(group);
                    model.setPercentX(percentX);
                    model.setPercentY(percentY);
                }

            }

            @Override
            public void onLongPress(final TagViewGroup group) {
                new AlertDialog.Builder(BLBeautifyImageActivity.this)
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                getCurrentFragment().removeTagGroup(group);
                                dialog.dismiss();
                            }
                        }).setTitle("删除标签组").setMessage("你确定要删除该标签组吗？")
                        .create().show();
            }
        };

    }

    public void setTitleText(int position) {
        btnEditPicTitle.setText("编辑照片(" + (position + 1) + "/" + imageList.size() + ")");
    }

    /**
     * 当照片页面被点击后，弹出标签编辑页面
     *
     * @param string
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onImageClick(String string) {
        if (string.equals(BLBeautifyFragment.class.getSimpleName())) {
            onCreateTagBtnClick();
        }
    }

    /**
     * 给fragment 添加tag
     *
     * @param tagGroupModel
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTagCreate(TagGroupModel tagGroupModel) {
        if (tagGroupModel != null) {
            getCurrentFragment().addTagGroup(tagGroupModel, mTagGroupClickListener);
        }
    }

    /**
     * 删除图片上的：经过编辑后的，原来的标签组
     *
     * @param deleteTagGroupEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeleteTagGroup(DeleteTagGroupEvent deleteTagGroupEvent){

        if (deleteTagGroupEvent != null){
            getCurrentFragment().removeTagGroupByTagModel(deleteTagGroupEvent.getTagGroupModel());
        }
    }


    @Override
    public void onClick(View v) {
        int resId = v.getId();
        if (resId == R.id.tv_cancle) {
            //取消编辑标签
            UIUtils.closeActivity(this);
        } else if (resId == R.id.tv_sure) {
            //确定添加标签: 每个fragment对应的图片，每个图片对应的tagmodel
            UIUtils.closeActivity(this);
        }
    }


    private BLBeautifyFragment getCurrentFragment() {
        Fragment f = fragments.get(curPosition);
        if (f instanceof BLBeautifyFragment) {
            return (BLBeautifyFragment) f;
        } else {
            return null;
        }
    }

    /**
     * 点击创建TagButton，跳转到Tag创建页面
     */
    private void onCreateTagBtnClick() {
        UIUtils.startActivity(this, AddTagActivity.class);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        finish();
        return super.onKeyDown(keyCode, event);
    }
}
